/**
 * @param {number[][]} mat
 * @return {number[][]}
 */
var updateMatrix = function(mat) {
  let visited = new Array(mat.length), direction = [[0, 1], [0, -1], [1, 0], [-1, 0]], queue = [];
  for(let i = 0; i < mat.length; i++) {
    visited[i] = new Array(mat[0].length).fill(false);
  }
  function isValid(i, j) {
    return i < mat.length && i >= 0 && j >= 0 && j < mat[0].length;
  }

  function impactOther(obj) {
    const { indexI, indexJ, level } = obj;
    for(let k = 0; k < direction.length; k++) {
      let newI = indexI + direction[k][0], newJ = indexJ + direction[k][1];
      if(isValid(newI, newJ) && !visited[newI][newJ] && mat[newI][newJ]) {
        mat[newI][newJ] = level + 1;
        queue.push({
          indexI: newI,
          indexJ: newJ,
          level: level + 1
        });
        visited[newI][newJ] = true;
      }
    }
  }

  for(let i = 0; i < mat.length; i++) {
    for(let j = 0; j < mat[0].length; j++) {
      if(mat[i][j] == 0) {
        visited[i][j] = true;
        queue.push({
          indexI: i,
          indexJ: j,
          level: 0
        });
      }
    }
  }

  while(queue.length) {
    const ele = queue.shift();
    impactOther(ele);
  }

  return mat;
};
let mat = [[0,0,0],[0,1,0],[0,0,0]];
console.log(updateMatrix(mat));
mat = [[0,0,0],[0,1,0],[1,1,1]];
console.log(updateMatrix(mat));
